package com.aispeech.task.fsm;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Pair;

@Slf4j
public class StateMachine<T> {
    private State state;
    private Event<T> event;

    public StateMachine(State initialState, Event initialEvent) {
        this.state = initialState;
        this.event = initialEvent;
    }

    public Event run() {
        while (true) {
            Pair<State, Event> next = state.transition(event);
            State nextState = next.getLeft();

//            log.warn("[ RUN ] Current(event: {}, state: {}) fired. next state: {}", event.eventType(), state, nextState);

            if (nextState == State.Invalid) {
                event.setType(EventType.Error);
                return event;
            } else if (nextState.isTerminal()) {
                return next.getRight();
            } else {
                event = next.getRight();
                state = nextState;
            }
        }
    }
}
